package cn.sc.summer.construction.sysimpl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import cn.sc.summer.constant.rabbit.RabbitConstant;
import cn.sc.summer.core.util.mail.EmailUtil;
import cn.sc.summer.rabbitmq.enums.RabbitErrorMessageTypeEnum;
import cn.sc.summer.rabbitmq.po.RabbitMessage;
import cn.sc.summer.rabbitmq.service.RabbitConsumerService;
import cn.sc.summer.rabbitmq.util.RabbitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 类名：登录异常接口实现类
 *
 * @author a-xin
 * @date 2023/10/20 13:08
 */
@Slf4j
@Service
public class LoginErrorImpl extends RabbitConsumerService {

    /**
     * 接口: 登录异常接口
     *
     * @param jsonStr 日志信息
     * @param message rabbit消息提
     * @param channel rabbit
     * @author a-xin
     * @date 2023/9/23 15:48
     */
    @RabbitListener(queues = RabbitConstant.LOGIN_RECORD_QUEUE)
    public void consumer(String jsonStr, Message message, Channel channel) {
        try {
            RabbitMessage<Map<String, Object>> stringRabbitMessage = RabbitUtil.checkMessage(jsonStr, new TypeReference<Map<String, Object>>() {});
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            if (stringRabbitMessage.getFlag()) {
                Map<String, Object> mapMessage = stringRabbitMessage.getMessage();
                Map<String, String> data = new ConcurrentHashMap<>();
                log.error("==> User login Error: UserName : {}, Account lock : {} Hours", mapMessage.get("phone"), mapMessage.get("failLock"));
                data.put("登录用户手机号", mapMessage.get("phone").toString());
                data.put("已登录失败次数", mapMessage.get("failMax") + "次");
                data.put("账号锁定时间", mapMessage.get("failLock") + "小时");
                data.put("最后一次登录时间", mapMessage.get("lastLogin").toString());
                EmailUtil.sendEmail("用户登录失败消息报告", data);
            } else {
                log.error("==> 接收到重复消费消息：Queue: {}, Exchange : {}, RoutingKey : {}, Message : {}",
                        RabbitConstant.LOGIN_RECORD_QUEUE,
                        RabbitConstant.LOGIN_RECORD_EXCHANGE,
                        RabbitConstant.LOGIN_RECORD_ROUTING_KEY,
                        jsonStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rabbitErrorService.exchangeMessage(e.getMessage(), jsonStr, RabbitErrorMessageTypeEnum.USER_LOGIN_ERROR);
        }
    }

}
